package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Filter;
/*
解决POST提交中文乱码过滤器
 */
@WebFilter(value ="/*",initParams = {@WebInitParam(name ="encoding",value ="UTF-8")})
public abstract class EncodingFilter implements Filter {
    private String encoding;
    public void init(FilterConfig filterConfig)throws ServletException{
        encoding =filterConfig.getInitParameter("encoding");
        System.out.println(encoding);
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException,ServletException{
        //对象的转换
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        HttpServletResponse response =(HttpServletResponse)servletResponse;
        //设置请求和响应的字符编码
        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);
        //放行
        filterChain.doFilter(request,response);
    }

}
